package zutils

import (
	"reflect"
	"strings"
)

func GetGormFields(stc any) []string{
	typ := reflect.TypeOf(stc)
	if typ.Kind() == reflect.Ptr {
		typ = typ.Elem()
	}

	if typ.Kind() == reflect.Struct {
		length := typ.NumField()
		columns := make([]string, 0, length)
		for i := 0; i < length; i++ {
			fieldType := typ.Field(i)
			if !fieldType.IsExported() {
				continue
			}

			if fieldType.Tag.Get("gorm") == "-" {
				continue
			}

			name := Camel2Snake(fieldType.Name)
			if len(fieldType.Tag.Get("gorm")) > 0 {
				content := fieldType.Tag.Get("gorm")
				if strings.HasPrefix(content, "column:") {
					content = content[7:]
					pos := strings.Index(content, ";")
					if pos > 0 {
						name = content[0 : pos]
					} else if pos < 0 {
						name = content
					}
				}
			}
			columns = append(columns, name)
		}
		return columns
	} else {
		return nil
	}
}
